package com.rivulet.foreign.controller;

import com.rivulet.foreign.pojo.Scholarship;
import com.rivulet.foreign.service.ScholarshipService;
import com.rivulet.foreign.service.ToolService;
import com.rivulet.foreign.tools.FileTool;
import com.rivulet.foreign.tools.Lock;
import com.rivulet.foreign.tools.Results;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

import static com.rivulet.foreign.tools.Identity.STUDENT;
import static com.rivulet.foreign.tools.Identity.TEACHER;

/**
 * {奖学金功能后端入口}
 *
 * @author xujiac
 * @create 2021/8/18
 * @since 1.0.0
 */
@RequestMapping(value = "/scholarship")
@RestController
public class ScholarshipController {
    @Value("${filepath}")
    String fileDirPath;

    final ScholarshipService scholarshipService;
    final ToolService authorizationForIdentity;

    public ScholarshipController(ScholarshipService scholarshipService, ToolService authorizationForIdentity) {
        this.scholarshipService = scholarshipService;
        this.authorizationForIdentity = authorizationForIdentity;
    }

    @RequestMapping(value = "/checkYet")
    public Results scholarshipCheckYet(@CookieValue("user_id")String user_id) {
        if (!authorizationForIdentity.reAuthorization(user_id, TEACHER)){
            return null;
        }
        Results results= scholarshipService.checkYetScholarship();
        return results;
    }

    @RequestMapping(value = "/apply")
    public Results scholarshipApply(@CookieValue("user_id")String user_id,
                                    @RequestParam("scholarship_type")Integer scholarship_type,
                                    @RequestParam("curriculum_number")Integer curriculum_number,
                                    @RequestParam("average_credit")Double average_credit,
                                    @RequestParam("gpa")Double gpa,
                                    @RequestParam("reason")String reason,
                                    @RequestParam("bonus_items_body") MultipartFile bonus_items_body,
                                    @RequestParam("bonus_items_practice") MultipartFile bonus_items_practice
    ){
        if (!authorizationForIdentity.reAuthorization(user_id, STUDENT)){
            return null;
        }
        Scholarship scholarship=new Scholarship(scholarship_type,curriculum_number,average_credit,gpa,reason);
        scholarship.setUser_id(Lock.lockOff(user_id));
        Results results;
        FileTool.FileDelete(fileDirPath,scholarship.getUser_id());
        if(
                FileTool.MultipartFileToFileSave(fileDirPath,scholarship.getUser_id(),bonus_items_body)
                        &&
                FileTool.MultipartFileToFileSave(fileDirPath,scholarship.getUser_id(),bonus_items_practice)
        ){
            scholarship.setBonus_items_body(bonus_items_body.getOriginalFilename());
            scholarship.setBonus_items_practice(bonus_items_practice.getOriginalFilename());
            results=scholarshipService.setScholarship(scholarship);
        }else {
            results=new Results(400,scholarship);
        }

        return results;
    }

    @RequestMapping(value = "/deal")
    public Results scholarshipDeal(@CookieValue("user_id")String user_id,@RequestBody Scholarship scholarship){
        if (!authorizationForIdentity.reAuthorization(user_id, TEACHER)){
            return null;
        }
        Results results =scholarshipService.dealScholarship(scholarship);
        return results;
    }
    @RequestMapping(value = "/check/{id}/{filename}")
    public void scholarshipFileGet(@PathVariable("filename") String filename, HttpServletResponse response, @CookieValue("user_id") String user_id, @PathVariable("id") String id) {
        if (!authorizationForIdentity.reAuthorization(user_id, TEACHER)) {
            return;
        }
        File file = new File(fileDirPath + id + File.separator + filename);
        if (file.exists()) {
            response.setContentType("application/octet-stream");
            try {
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            byte[] buffer = new byte[1024];

            OutputStream os = null;
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
